import { ResourceDownloaderService } from '../services/resource-downloader.service';
import { ResourceInfo } from '../types/resource.types';

// 模拟资源数据
const testResources: ResourceInfo[] = [
  {
    originalUrl: 'https://cdn.appthen.com/Fp_s_XBf9C1PhnPplQWi0Udx8cw4',
    localPath: 'resources/other/test/Fp_s_XBf9C1PhnPplQWi0Udx8cw4',
    type: 'other' as any,
    source: 'cdn' as any,
    pathInProject: '/Fp_s_XBf9C1PhnPplQWi0Udx8cw4'
  },
  {
    originalUrl: 'https://cdn.appthen.com/Fmk8IZVxeE9QYk9hKJM-D2L4Q52_',
    localPath: 'resources/image/test/Fmk8IZVxeE9QYk9hKJM-D2L4Q52_',
    type: 'image' as any,
    source: 'cdn' as any,
    pathInProject: '/Fmk8IZVxeE9QYk9hKJM-D2L4Q52_'
  },
  {
    originalUrl: 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js',
    localPath: 'resources/script/test/jweixin-1.6.0.js',
    type: 'script' as any,
    source: 'external' as any,
    pathInProject: '/open/js/jweixin-1.6.0.js'
  }
];

async function runFinalTest() {
  console.log('=== 最终下载测试 ===\n');

  // 创建临时目录
  const fs = require('fs');
  const path = require('path');
  const os = require('os');

  const tempDir = path.join(os.tmpdir(), `resource-test-${Date.now()}`);
  if (!fs.existsSync(tempDir)) {
    fs.mkdirSync(tempDir, { recursive: true });
  }

  console.log(`临时目录: ${tempDir}`);

  const downloader = new ResourceDownloaderService();

  try {
    console.log('\n开始下载测试...');
    const result = await downloader.downloadResources(testResources, tempDir);

    console.log(`\n=== 下载结果 ===`);
    console.log(`成功: ${result.downloaded.length} 个`);
    console.log(`失败: ${result.failed.length} 个`);

    if (result.downloaded.length > 0) {
      console.log('\n成功下载的文件:');
      result.downloaded.forEach((resource, index) => {
        const fs = require('fs');
        const path = require('path');
        const filePath = path.join(tempDir, resource.localPath);
        const exists = fs.existsSync(filePath);
        const stats = exists ? fs.statSync(filePath) : null;

        console.log(`  ${index + 1}. ${resource.originalUrl}`);
        console.log(`     类型: ${resource.type}`);
        console.log(`     大小: ${resource.size || (stats?.size || 0)} bytes`);
        console.log(`     文件存在: ${exists ? '✅' : '❌'}`);
        console.log('');
      });
    }

    if (result.failed.length > 0) {
      console.log('\n失败的文件:');
      result.failed.forEach(({ resource, error }, index) => {
        console.log(`  ${index + 1}. ${resource.originalUrl}`);
        console.log(`     错误: ${error}`);
        console.log('');
      });
    }

    // 检查文件完整性
    console.log('\n=== 文件完整性检查 ===');
    let totalSize = 0;
    let validFiles = 0;

    result.downloaded.forEach(resource => {
      const filePath = path.join(tempDir, resource.localPath);
      if (fs.existsSync(filePath)) {
        const stats = fs.statSync(filePath);
        totalSize += stats.size;
        validFiles++;

        console.log(`✅ ${resource.originalUrl}`);
        console.log(`   文件: ${resource.localPath}`);
        console.log(`   大小: ${stats.size} bytes`);
        console.log('');
      } else {
        console.log(`❌ 文件不存在: ${resource.localPath}`);
      }
    });

    console.log(`\n=== 统计信息 ===`);
    console.log(`有效文件: ${validFiles}/${result.downloaded.length}`);
    console.log(`总大小: ${(totalSize / 1024 / 1024).toFixed(2)} MB`);
    console.log(`平均大小: ${(totalSize / validFiles / 1024).toFixed(2)} KB`);

    // 清理临时文件
    console.log('\n清理临时文件...');
    const rimraf = require('rimraf');
    rimraf.sync(tempDir);
    console.log('清理完成');

  } catch (error) {
    console.error('测试失败:', error);
  }
}

// 运行测试
if (require.main === module) {
  runFinalTest().catch(console.error);
}

export { runFinalTest };